#include "diskTest.h"

static char byte_unit(uint64_t where) {
        char there = 0;
        // 不要1.23MiB这样
        while (where & ~((1<<11) - 1)) {
                where >>= 10;
                there++;
        }
        return there;
}
static char min8(char a, char b) {
        return a < b ? a : b;
}
static void byte_unit_human(uint64_t byte) {
        char *unit_name[] = {NULL, "KiB", "MiB", "GiB", "TiB", "PiB"};
        char which_unit = min8(byte_unit(byte), 5);
        if (which_unit == 0)
                printf("%zd", byte);
        else
                printf("%zd(%.2lf%s)", byte, (double)byte / ((uint64_t)1 << (10 * which_unit)), unit_name[(int)which_unit]);
}

// B!, :123, 23 / 40, 57%
// :123, 23 / 40, 57%
// 23 / 40, 57%
static void _progress(void) {
        // FIXME
        if (*break_point != -1)
                printf("B!, ");
        if (opt.started) {
                printf(":");
                byte_unit_human(*head);
                printf(", ");
        }
        byte_unit_human(*head - opt.start);
        printf(" / ");
        size_t size = opt.end - opt.start + 1;
        byte_unit_human(size);
        printf(", %d%%", (int)(100.0 * (*head - opt.start) / size));
#       ifdef _DEBUG
        printf("PPID: %d, PID: %d", getppid(), getpid());
#       endif
        putchar('\r');
        fflush(stdout);
}

void loop_progress(void) {
        while (1) {
#               ifndef _DEBUG
                        sleep(1);
#               endif
                if (getppid() != main_pid)
                        _exit(0);
                _progress();
        }
}
